<?php
/**
 * Ecart
 *
 * This file is part of Ecart.
 *
 * Ecart is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Ecart is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Ecart.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category    Ecart
 * @package     Ecart_Catalog
 * @copyright   Copyright 2008-2009 E-Cart LLC
 * @license     GNU Public License V3.0
 */

/**
 *
 * @category    Ecart
 * @package     Ecart_Catalog
 * @subpackage  Controller
 * @author      Ecart Core Team <core@ecartcommerce.com>
 */

class Ecart_Catalog_IndexController extends Ecart_Core_Controller_Front
{
    public function init()
    {
        parent::init();
        $this->hurl = Ecart_HumanUri::getInstance();
        $this->view->crumbs()->add(
            Ecart::translate('catalog')->__('Catalog'),
            '/' . $this->view->catalogUrl
        );
        $this->view->tags()->disableAction();
    }

    protected function _initCategory($id)
    {
        $categoryRow = Ecart::single('catalog/category')->find($id)->current();

        if (!$categoryRow || $categoryRow->status != 'enabled') {
            return false;
        }

        $parentItems = $categoryRow->cache()->getParentItems();
        foreach ($parentItems as $item) {
            if ($item['status'] != 'enabled') {
                return false;
            }
            $this->view->crumbs()->add(
                $item['name'],
                $this->view->hurl(array(
                    'cat' => array(
                        'value' => $item['id'],
                        'seo'   => $item['key_word']
                    )
                )));
        }

        $categoryDescriptionRow = Ecart::single('catalog/category_description')
            ->find($id, Ecart_Locale::getLanguageId())
            ->current();

        if (!$categoryDescriptionRow) {
            return false;
        } else {
            $this->view->category = array_merge(
                $categoryRow->toArray(),
                $categoryDescriptionRow->toArray()
            );
            $this->view->pageTitle = $categoryDescriptionRow->name;
            $this->view->meta()->set(array(
                'description'   => $categoryDescriptionRow->meta_description,
                'title'         => $categoryDescriptionRow->meta_title,
                'keywords'      => $categoryDescriptionRow->meta_keyword
            ));
        }

        Zend_Registry::set('catalog/current_category', $this->view->category);

        return $this->view->category;
    }

    /**
     *  View category action (listing product)
     */
    public function viewAction()
    {
        if ($this->hurl->hasParam('product') || $this->getRequest()->getParam('product')) {
            $this->_request->setActionName('product');
            return $this->productAction();
        }

        $filters = array('site_ids' => Ecart::getSiteId());

        $this->view->pageTitle = Ecart::translate('catalog')->__('Catalog');

        if ($this->hurl->hasParam('cat')) {
            if (!$category = $this->_initCategory($this->hurl->getParamValue('cat'))) {
                return $this->_forward('not-found', 'Error', 'Ecart_Core');
            }
            $filters['category_ids'] = $category['id'];
        }

        if ($this->hurl->hasParam('manufacturer')) {
            $filters['manufacturer_ids'] = $this->hurl->getParamValue('manufacturer');
        }

        if ($this->hurl->hasParam('price')) {
            list($from, $to) = explode(',', $this->hurl->getParam('price'));
            $filters['price'] = array(
                'from'  => $from,
                'to'    => $to
            );
        }

        if ($this->hurl->hasParam('attributes')) {
            $filters['attributes'] = $this->hurl->getAttributeIds();
        }

        $paging = array();
        $paging['page'] = (int) $this->hurl->getParam('page', 1);
        if ($paging['page'] < 1) {
            $paging['page'] = 1;
        }

        $paging['perPage'] = array();
        foreach (explode(',', Ecart::config('catalog/listing/perPage')) as $perPage) {
            $optionValue = $this->view->hurl(array('limit' => $perPage, 'page' => null));
            $paging['perPage'][$optionValue] = $perPage;
        }

        $paging['sortBy'] = array();
        foreach (explode(',', Ecart::config('catalog/listing/sortBy')) as $order) {
            $optionValue = $this->view->hurl(array('order' => strtolower($order), 'page' => null));
            $optionText = Ecart::translate('catalog')->__($order);
            $paging['sortBy'][$optionValue] = $optionText;
        }

        if ($this->hurl->hasParam('limit')
            && in_array($this->hurl->getParam('limit'), $paging['perPage'])) {

            $paging['limit'] = $this->hurl->getParam('limit');
        } elseif (Ecart::session('catalog')->limit) {
            $paging['limit'] = Ecart::session('catalog')->limit;
        } else {
            $paging['limit'] = Ecart::config('catalog/listing/perPageDefault');
        }
        Ecart::session('catalog')->limit = $paging['limit'];

        if ($this->hurl->hasParam('order')
            && in_array($this->hurl->getParam('order'), array('name', 'price'))) {

            $paging['order'] = $this->hurl->getParam('order');
        } elseif (Ecart::session('catalog')->order) {
            $paging['order'] = Ecart::session('catalog')->order;
        } else {
            $paging['order'] = 'name';
        }
        Ecart::session('catalog')->order = $paging['order'];

        if ($this->hurl->hasParam('dir')
            && in_array($this->hurl->getParam('dir'), array('desc', 'asc'))) {

            $paging['dir'] = $this->hurl->getParam('dir');
        } elseif (Ecart::session('catalog')->dir) {
            $paging['dir'] = Ecart::session('catalog')->dir;
        } else {
            $paging['dir'] = 'asc';
        }
        Ecart::session('catalog')->dir = $paging['dir'];

        switch ($paging['order']) {
            case 'name':
                $order = 'cpd.name';
                break;
            case 'price':
                $order = 'cp.price';
                break;
        }

        $productList = Ecart::single('catalog/product')->getList(
            $filters,
            $order . ' ' . $paging['dir'],
            $paging['limit'] == 'all' ? 0 :  $paging['limit'],
            ($paging['page'] - 1) * ($paging['limit'] == 'all' ? 0 : $paging['limit'])
        );

        $paging['count'] = $productList['count'];
        $this->view->products = $productList['products'];

        $paging['pages'] = 1;
        if ($paging['limit'] != 'all') {
            $paging['pages'] = ceil($paging['count'] / $paging['limit']);
        }

        $this->view->paging = $paging;
        if ($this->hurl->hasParam('mode')) {
            $mode = $this->hurl->getParam('mode');
        } elseif (Ecart::session('catalog')->mode) {
            $mode = Ecart::session('catalog')->mode;
        } else {
            $mode = Ecart::config()->catalog->listing->type;
        }
        $this->view->mode = $mode;
        Ecart::session('catalog')->mode = $mode;

        $this->render('listing');
    }

    public function productAction()
    {
        $productId = $this->hurl->getParamValue('product');
        if (!$productId) {
            $productId = $this->_getParam('product', 0);
        }
        /**
         * @var $product Ecart_Catalog_Model_Product_Row
         */
        $product = Ecart::single('catalog/product')
            ->cache($productId /*Ecart::getCustomerId()*/)
            ->find($productId)
            ->current();

        if (!$product || !$product->is_active) {
            return $this->_forward('not-found', 'Error', 'Ecart_Core');
        }

        $categoryId = null;
        if ($referer = $this->getRequest()->getServer('HTTP_REFERER')) {
            preg_match(
                '/' . $this->view->catalogUrl . '\/(.[^\/]+)\//',
                $referer,
                $categoryUrl
            );
            if (isset($categoryUrl[1])) {
                $categoryId = Ecart::single('catalog/category')
                    ->cache($categoryUrl/*, Ecart::getCustomerId()*/)
                    ->getIdByUrl($categoryUrl[1], Ecart::getSiteId());
            }
        }

        if (is_numeric($categoryId)) {
            $pathItems = $product->getParentItems($categoryId);
        } else {
            $pathItems = $product->getParentItems();
        }

        foreach ($pathItems as $item) {
            if ($item['status'] != 'enabled') {
                return $this->_forward('not-found', 'Error', 'Ecart_Core');
            }
            $this->view->crumbs()->add(
                $item['name'],
                $this->view->hurl(array(
                    'cat' => array(
                        'value' => $item['id'],
                        'seo' => $item['key_word']
                    )
                ), false, true)
            );
            Zend_Registry::set('catalog/current_category', $item['id']);
        }

        $product->incViewed();
        Zend_Registry::set('catalog/current_product', $productId);

        $data = $product->toArray();
        $data['images'] = Ecart::single('catalog/product_image')
            ->cache($productId)
            ->getList($productId);
        $data['images'] = current($data['images']);
        $data['human_url']   = urlencode($this->hurl->getParamSeo('product'));
        $data['description'] = $product->cache($productId)->getDescription();
        $data['properties']  = $product->cache($productId)->getProperties();
        $data['modifiers']   = $product->cache($productId)->getModifiers();
        foreach ($product->cache()->getVariationAttributesData() as $key => $value) {
            $data[$key] = $value;
        }
        $data['stock'] = array();
        $data['stock']['quantity'] = $data['quantity'];
        $data['stock']['is_saleable'] = (int)$product->cache($productId)->isSaleable();
        $stock = Ecart::single('catalog/product_stock')
            ->cache($productId)
            ->find($productId)
            ->current()
            ->toArray();
        $data['stock'] = array_merge($stock, $data['stock']);

        unset($data['quantity']);

        $data['price_discount'] = $product->getPrice();

        $data['price'] = $product->getPriceRules();

        $data['discount_rules'] = Ecart::single('discount/discount')
            ->cache($productId)
            ->getRulesByProductId($productId);

        $data['price']['format'] = Ecart::single('locale/currency')
            ->getFormat();

//        Zend_Debug::dump($data);
        $this->view->product = $data;

        $this->view->crumbs()->add($data['description']['name']);
        $this->view->pageTitle = $data['description']['name'];

        $metaTitle = trim($data['description']['meta_title']) == '' ?
            $data['description']['name'] : $data['description']['meta_title'];

        $metaDescription = trim($data['description']['meta_description']) == '' ?
            strip_tags($data['description']['description']) :
                strip_tags($data['description']['meta_description']);

        $this->view->meta()
            ->setTitle($metaTitle, 'product', $productId)
            ->setDescription($metaDescription)
            ->setKeywords($data['description']['meta_keyword'])
        ;

        Ecart::dispatch('catalog_product_view', array(
            'product' => $product
        ));

        $this->render('product');
    }

    public function __call($method, $args)
    {
        $this->_request->setActionName('view');
        $this->viewAction();
    }
}